<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/23
 * Time: 16:08
 */

namespace app\admin\logic;

use think\Db;
use think\Loader;

class Menu
{
    /**
     * 生成权限树
     * @param $role_id
     * @return array
     */
    public function getTree($role_id)
    {
        //顶级菜单
        $top_menu = Loader::model('Menus')->getChildMenu();
        //菜单节点信息
        $where['status'] = 1;
        //如果是超级管理员，则可以看到所有菜单（目前暂时先取所有菜单）
        /*
        if(Session::has(Config::get('rbac.admin_auth_key'))){
            $menu = Db::name("menus")->where($where)->field("*")->order("order_no DESC")->select();
        }else{
            //当前登录管理员
            $operator_id = Session::get(Config::get('rbac.user_auth_key'));
            //获取管理员已有角色
            $role_ids = Db::name('role_operators')->where('operator_id', $operator_id)->column('role_id');
            //获取角色所拥有的菜单
            $menu_ids = Db::name('role_menus')->whereIn('role_id',$role_ids)->column('menu_id');
            $menu = Db::name("menus")->where($where)->whereIn('id', $menu_ids)->field("*")->order("order_no DESC")->select();
        }*/
        $menu = Db::name("menus")->where($where)->field("*")->order("order_no DESC")->select();
        $accesses = Db::name("role_menus")->where("role_id", $role_id)->column('menu_id');
        //生成wdTree插件需要的数据格式
        $menu_tree = [];
        foreach ($menu as $v) {
            $menu_tree[] = [
                "id" => $v['id'],
                "pid" => $v['pid'],
                "text" => $v['name'] . ($v['menu_url'] ? " (" . $v['menu_url'] . ") " : "") . (isset($top_menu[$v['pid']]) ? '<span style="color:red">[ ' . $top_menu[$v['pid']] . ' ]</span>' : ''),
                //"value" => $v['id'] . "_" . $v['level'] . "_" . $v['pid'],
                "value" => $v['id'],
                "showcheck" => true,
                'checkstate' => in_array($v['id'], $accesses) ? 1 : 0,
                'hasChildren' => ($v['level'] != 3) ? true : false,
                'isexpand' => true,
                'complete' => true,
            ];
        }

        //生成树
        return list_to_tree($menu_tree, "id", "pid", "ChildNodes");
    }
}